﻿/*
*类名：QinMingWeixinOAuth
*归属：QinMing.WeixinOAuth命名空间
*用途：通过网页OAuth方式获取用户openid和access_token，进而可以获取微信用户的头像、昵称等信息
*作者：乱世刀疤
*日期：2020.05.08
*/

using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;  
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
using QinMing.Config;
using QinMing.Tools.DB;

namespace QinMing.WeixinOAuth
{
    public  class QinMingWeixinOAuth : System.Web.UI.Page
    {
		
		/// <summary>
        /// 获取CODE，后期用于获取微信用户openid，静默，不需要用户确认
        /// </summary>
		public string GetCodeBase(string appid, string redirect_url)
		{
			var state = "QinMing" + DateTime.Now.Millisecond;
			string RedirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" 
			    + "appid=" + appid 
				+ "&redirect_uri=" + redirect_url
				+ "&response_type=code&scope=snsapi_base"
				+ "&state=" + state + "#wechat_redirect";
			
			return RedirectUrl;
		}
		
		/// <summary>
        /// 用CODE换取openid，适用于获取用户openid，在scope=snsapi_base使用
        /// </summary>
		public string GetOpenId(string code)
	    {
			string appid = QinMingConfig.Weixin_AppId;
			string secret = QinMingConfig.Weixin_AppSecret;
			string strResult="";
			string openid="";
			string strurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="
			    + appid + "&secret="
				+ secret + "&code="
				+ code + "&grant_type=authorization_code";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();
				
				JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				openid = obj["openid"].ToString().Replace("\"", "");
				return openid;
			}
			catch
			{
			    strResult = "err";
				return strResult;
			}
	    }
		
		/// <summary>
        /// 获取CODE，后期用于获取微信用户信息，需要用户确认；与上面GetCodeBase的差异只是scope=snsapi_userinfo部分
        /// </summary>
		public string GetCodeUserInfo(string appid, string redirect_url)
		{
			var state = "QinMing" + DateTime.Now.Millisecond;
			string RedirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" 
			    + "appid=" + appid 
				+ "&redirect_uri=" + redirect_url
				+ "&response_type=code&scope=snsapi_userinfo"
				+ "&state=" + state + "#wechat_redirect";
			
			return RedirectUrl;
		}
		
		/// <summary>
        /// 用CODE换取openid和AccessToken，适用于获取用户信息，在scope=snsapi_userinfo使用，切忌只能用在服务器端使用，不能传递到客户端，高风险
        /// </summary>
		public string GetOpenIdAndAccessToken(string code)
	    {
            string appid = QinMingConfig.Weixin_AppId;
			string secret = QinMingConfig.Weixin_AppSecret;
			string strResult="";
			string openid="";
			string access_token="";
			string strurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="
			    + appid + "&secret="
				+ secret + "&code="
				+ code + "&grant_type=authorization_code";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();
				
				JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				openid = obj["openid"].ToString().Replace("\"", "");
				access_token = obj["access_token"].ToString().Replace("\"", "");
				return openid + "|" + access_token;
			}
			catch
			{
			    strResult = "err";
				return strResult;
			}
			
	    }
		
		/// <summary>
        /// 获取用户信息，包含头像和昵称等
        /// </summary>
		public JObject GetUserInfo(string open_id, string access_token)
	    {
			string strResult = "";
			string strurl="https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + open_id + "&lang=zh_CN";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();

				//更新weixin_user_info表中微信用户信息
				JObject tmpobj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				QinMingToolsDB.UpdateTable("update weixin_user_info set nickname='" + tmpobj["nickname"].ToString().Replace("\"", "") + "',"
				    + "headimgurl='" + tmpobj["headimgurl"].ToString().Replace("\"", "") + "',"
					+ "province='" + tmpobj["province"].ToString().Replace("\"", "") + "',"
					+ "city='" + tmpobj["city"].ToString().Replace("\"", "") + "',"
					+ "country='" + tmpobj["country"].ToString().Replace("\"", "") + "',"
					+ "sex='" + tmpobj["sex"].ToString().Replace("\"", "") + "' "
				    + " where openid='" + open_id + "'");
			}
			catch
			{
				strResult = "err";
			}
			JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
			return obj;
	    }
		/*
		//正确返回时JObject格式如下
		{   
			"openid": "OPENID",
			"nickname": NICKNAME,
			"sex": 1,
			"province":"PROVINCE",
			"city":"CITY",
			"country":"COUNTRY",
			"headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
			"privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
			"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
		}
		*/

	}
	
	
}